
from rest_framework import serializers
from users.models import User
from django.contrib.auth.models import Group


class AdminGroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = [
            'id',
            'name'
        ]


class AdminUserModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = [
            'id',
            'username',
            'email',
            'mobile',

            'password',

            # ManyToManyField类型字段
            'groups',
            'user_permissions'
        ]

        extra_kwargs = {
            'password': {'write_only': True}
        }

    def validate(self, attrs):
        # TODO: 在校验的过程中加密密码，以及补充有效数据is_staff=True; 好处是可以同时作用与后续的新建和更新
        from django.contrib.auth.hashers import make_password
        # 1、密码加密
        raw_password = attrs.get('password') # 明文密码
        password = make_password(raw_password) # make_password是django内置全局用户密码加密函数
        attrs['password'] = password # 把有效数据中的明文密码覆盖为密文密码
        # 2、补充is_staff=True有效数据
        attrs['is_staff'] = True
        return attrs
